import React from "react";
import { sleep } from 'antd-mobile/es/utils/sleep';
import styles from '@/assets/css/order.module.css';
import type order from "@/types/order";

interface Order extends order{
    comment_status:boolean;
}

interface comment{
    rate:number;
    content:string;
    orderid:number;
    busid:number;
}

export default function Index()
{
    const [active,SetActive] = useState<string>('all');
    const [list,SetList] = useState<Order[]>([]);
    const [HasMore,SetHasMore] = useState<boolean>(true);
    const [page,SetPage] = useState<number>(1);
    const [RateShow, SetRateShow] = React.useState(false);
    // 表单实例
    const [form] = React.UI.Form.useForm();
    const [comment] = useState({rate: 5, content: ''});
    const [orderid, SetOrderID] = useState(0);

    // 下拉刷新事件
    const OnRefresh = async () =>
    {
        await sleep(1500);
        SetList([]);
        SetPage(1);
        SetHasMore(true);
    }

    // 上拉加载事件
    const OnLoadMore = async () =>
    {
        await sleep(1500);
        await GetOrderData();
    }

    // 获取订单数据
    const GetOrderData = async () =>
    {
        const params = {
            busid:React.business.id,
            status:active,
            page
        }

        const result = await React.http.post('/order/index',params);

        if(result.code === 1)
        {
            const DataCount = result.data.count;
            let ListCount = 0;

            SetList(v =>
            {
                const data = [...v,...result.data.list];

                ListCount = data.length;

                return data;
            });

            if(ListCount >= DataCount)
            {
                SetHasMore(false);

                return false;
            }

            SetPage(val => val + 1);
        }else{
            SetHasMore(false);

            React.fail(result.msg);
        }
    }

    // 切换tab
    const OnTabChange = (value:string) =>
    {
        SetActive(value);
        OnRefresh();
    }

    // 申请退款
    const OnApplyRefund = (id:number) =>
    {
        React.UI.Dialog.confirm({
            title: '退款提醒',
            content: '是否确认申请退款',
            onConfirm:async () =>
            {
                const params = {
                    busid:React.business.id,
                    orderid:id
                }

                const result = await React.http.post('/order/refund',params);

                if(result.code === 1)
                {
                    React.success(result.msg,() => OnRefresh());
                }else
                {
                    React.fail(result.msg);
                }
            }
        })
    }

    const OnCommentChange = (id:number) =>
    {
        SetOrderID(id);
        SetRateShow(true);
    }

    const OnSubmit = async (values:comment) =>
    {
        SetRateShow(false);

        values.orderid = orderid
        values.busid = React.business.id
        
        const result = await React.http.post('/order/comment', values)

        if(result.code === 1)
        {
            React.success(result.msg, () => OnRefresh());
        }else{
            React.fail(result.msg)
        }
    }

    // 按钮结构
    const ButtonList = ({order}:{order:Order}) => 
    {
        if(order.status == '1')  //已支付
        {
            return (
                <React.UI.Button color='danger' size='small' onClick={() => OnApplyRefund(order.id)}>申请退款</React.UI.Button>
            )
        }

        // 已退房，但是还没评价
        if(order.status == '3' && !order.comment_status)
        {
            return (<React.UI.Button color='warning' size='small' onClick={() => OnCommentChange(order.id)}>立即评价</React.UI.Button>)
        }

        if(order.status == '-1')
        {
            return (<React.UI.Button color="warning" size="small">申请退款中...</React.UI.Button>)
        }
    }

    return (
        <>
            {/* 选项卡切换 */}
            <React.UI.Tabs onChange={OnTabChange} style={{backgroundColor: '#fff'}} activeKey={active} activeLineMode={'full'}>
                <React.UI.Tabs.Tab title="全部" key="all" />
                <React.UI.Tabs.Tab title="已支付" key="1" />
                <React.UI.Tabs.Tab title="已入住" key="2" />
                <React.UI.Tabs.Tab title="已退房" key="3" />
                <React.UI.Tabs.Tab title="已评价" key="4" />
                <React.UI.Tabs.Tab title="售后" key="-1" />
            </React.UI.Tabs>

            <div style={{height:'10px'}}></div>

            {/* 下拉刷新列表 */}
            <React.UI.PullToRefresh onRefresh={OnRefresh}>
                {/* 订单列表 */}
                <div className={styles.order_list}>
                    {list && list.map((item: order, key: number) =>
                        <div className={styles.item} key={key}>
                            <div className={styles.item_top}>
                                <p>{item.room.name}</p>
                                <div className={styles.top_tag}>{item.status_text}</div>
                            </div>

                            <div className={styles.house}>
                                <div className={styles.item_swipers}>
                                    <img src={item.room.thumb_text} alt="" />
                                </div>
                                <div className={styles.item_times}>
                                    <div>
                                        <div>{item.starttime_text}</div>
                                        <div>{item.startday_text}</div>
                                    </div>
                                    <div>
                                        <div>共{item.order_day}晚</div>
                                        <div className={styles.item_right}>
                                            <img src={'/assets/images/right1.png'} alt="" />
                                        </div>
                                    </div>
                                    <div>
                                        <div>{item.endtime_text}</div>
                                        <div>{item.endday_text}</div>
                                    </div>
                                    <div>
                                        <div className={styles.item_pay}>订单总价</div>
                                        <div className={styles.item_price}>￥{item.price}</div>
                                    </div>
                                </div>
                            </div>

                            <div className={styles.item_bar}>
                                
                                {/* {ButtonList(item)} */}
                                <ButtonList order={item as Order} />

                                <React.UI.Button color='primary' size='small' onClick={() => React.navigate(`/order/info?orderid=${item.id}`)}>
                                    查看详情
                                </React.UI.Button>
                            </div>
                        </div>
                    )}
                </div>

                {/* 上拉加载 */}
                <React.UI.InfiniteScroll loadMore={OnLoadMore} hasMore={HasMore} threshold={0} />
            </React.UI.PullToRefresh>

            <React.UI.Popup
                visible={RateShow}
                onMaskClick={() => SetRateShow(false)}
                onClose={() => SetRateShow(false)}
                style={{borderRadius: '10px'}}
            >
                <React.UI.Form
                    form={form}
                    name="comment"
                    layout="horizontal"
                    mode="card"
                    initialValues={comment}
                    onFinish={OnSubmit}
                    footer={<React.UI.Button block type='submit' color='primary' size='large'>提交</React.UI.Button>}
                >
                    <React.UI.Form.Item name="content" label="评价内容" rules={[{required: true, message: '请输入评价内容'}]}>
                        <React.UI.TextArea maxLength={100} rows={2} showCount placeholder="请输入评价内容" />
                    </React.UI.Form.Item>

                    <React.UI.Form.Item name="rate" label="评分" rules={[{required: true, message: '请选择评分'}]}>
                        <React.UI.Rate />
                    </React.UI.Form.Item>
                </React.UI.Form>

            </React.UI.Popup>
        </>
    )
}